package com.example.helloworldtext2.fragments;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.helloworldtext2.R;
import com.example.helloworldtext2.adapter.VideoAdapter;
import com.example.helloworldtext2.api.ArticleApi;
import com.example.helloworldtext2.model.Article;
import com.example.helloworldtext2.utils.VideoPlayManager;
import com.google.android.exoplayer2.ui.StyledPlayerView;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

public class VideoFragment extends Fragment {
    
    private static final String TAG = "VideoFragment";
    private ViewPager2 viewPager;
    private List<Article> videoList;
    private ArticleApi articleApi;
    private int currentPage = 1;
    private boolean isLoading = false;
    private boolean hasMoreData = true;
//    private SimpleCache simpleCache;
    private final Object cacheLock = new Object(); // 添加缓存同步锁
    private VideoAdapter videoAdapter;
    private Context context;
    private boolean onFragmentResume;
    private boolean onFragmentVisible;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_video, container, false);
        context = getActivity();
        articleApi = new ArticleApi();
        videoList = new ArrayList<>();
        loadVideoData();
        initViews(view);

        return view;
    }

    private void initViews(View view) {
        viewPager = view.findViewById(R.id.viewPager);
        SeekBar videoProgress = view.findViewById(R.id.videoProgress);

        videoAdapter = new VideoAdapter(context,videoList);
        viewPager.setAdapter(videoAdapter);
         viewPager.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        
         // 设置页面切换监听器
         viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
             @Override
             public void onPageSelected(int position) {
                super.onPageSelected(position);
                Log.d("sdfs","切换页面");
                
                // 添加空值检查，确保itemView不为空
                View itemView = viewPager.findViewWithTag(position);
                if (itemView != null && position < videoList.size()) {
                    Article article = videoList.get(position);
//                    获取元素
                    StyledPlayerView playerView = itemView.findViewById(R.id.videoView);
                    ImageView playButton = itemView.findViewById(R.id.playButton);
                    ImageView coverImage = itemView.findViewById(R.id.coverImage);
                    if (playerView != null) {
                        VideoPlayManager.getInstance(getContext()).setCurVideoPlayTask(article, playerView, videoProgress, playButton, coverImage).startPlay();
                    }
                }
                
                // 当滚动到末尾时加载更多数据
                if (position >= videoList.size() - 1 && !isLoading && hasMoreData) {
                    loadNextPage();
                }
             }
         });
    }
//    数据初始化
    private void loadVideoData() {
        // 清空现有数据
        if(videoList.size()>0){
            videoList.clear();
        }

        currentPage = 1;
        hasMoreData = true;

        // 发起网络请求获取视频数据
        fetchVideoDataFromAPI(currentPage);
    }
//    获取视频数据
    private void fetchVideoDataFromAPI(int page) {
        if (isLoading || !hasMoreData) {
            return;
        }

        isLoading = true;

        articleApi.getVideoList(page, 10, new ArticleApi.VideoListListener() {
            @Override
            public void onSuccess(JSONArray videoArray, int page, boolean hasMore) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        try {
                            List<Article> articles = articleApi.parseVideoData(videoArray);
                            updateVideoData(articles, page);
                            // 更新分页信息
                            currentPage = page;
                            hasMoreData = hasMore;
                            isLoading = false;
                        } catch (JSONException e) {
                            Log.e(TAG, "Error parsing video data", e);
                            isLoading = false;
                            Toast.makeText(getContext(), "解析视频数据失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onError(String error) {
                Log.e(TAG, "Failed to fetch video data: " + error);
                isLoading = false;
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "获取视频数据失败: " + error, Toast.LENGTH_SHORT).show();
                        // 第一页加载失败时加载示例数据
//                        if (page == 1) {
//                            loadSampleData();
//                        }
                    });
                }
            }
        });
    }
    
    //更新视频数据
    private void updateVideoData(List<Article> articles, int page) {
        // 如果是第一页，清空现有数据
        if (page == 1) {
            videoList.clear();
        }
        
        videoList.addAll(articles);
        Log.d("sdfsdsd","视频" + videoList.size());

        videoAdapter.notifyDataSetChanged();
    }
    // 加载下一页数据
    private void loadNextPage() {
        if (!isLoading && hasMoreData) {
            fetchVideoDataFromAPI(currentPage + 1);
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 使用同步块保护SimpleCache的释放
        Log.d("onDestroy","8989898988");
        videoList.clear();
        videoAdapter.notifyDataSetChanged();
    }

//    @Override
//    public void onPause() {
//        super.onPause();
//        // 页面暂停时停止所有视频播放
//        if (videoAdapter != null) {
//            videoAdapter.pauseAllVideos();
//        }
//    }

//    @Override
//    public void onDestroyView() {
//        super.onDestroyView();
//        // 页面销毁时停止所有视频播放
//        if (videoAdapter != null) {
//            videoAdapter.releaseAllPlayers();
//        }
//    }
    @Override
    public void onResume() {
        super.onResume();
        onFragmentResume = true;
        if(onFragmentVisible) {
            VideoPlayManager.getInstance(getActivity()).resumePlay();
        }
        Log.d("Video_Play_TAG", " video fragment Resume ");
    }

    @Override
    public void onPause() {
        super.onPause();
        onFragmentResume = false;
        VideoPlayManager.getInstance(getActivity()).pausePlay();
        Log.d("Video_Play_TAG", " video fragment Pause ");
    }
}